package com.uzai.console.service.kuizhan.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.mapper.SysConfigMapper;
import com.uzai.console.service.kuizhan.KuaiZhanService;
import com.uzai.console.vo.kuaizhan.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 快站域名管理实现类
 * @author liuqi
 * @date 2022年01月16日 17:14
 */
@Service
public class KuaiZhanServiceImpl implements KuaiZhanService {

    Logger logger = LoggerFactory.getLogger(KuaiZhanServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    /**
     * 封装快站请求签名方法
     * @author jitwxs
     * @date 2022/1/16 17:19
     * @param params
     * @param secret
     * @return java.lang.String
     */
    private String signTopRequest(Map<String, String> params, String secret) {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);

        for (String key : keys) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value) && !"sign".equals(key)) {
                query.append(key).append(value);
            }
        }

        query.append(secret);

        // 第三步：使用MD5加密
        return DigestUtils.md5Hex(query.toString());
    }

    /**
     * 根据站点id请求快站站点信息
     * @author jitwxs
     * @param siteId-站点ID
     * @date 2022/1/16 17:16
     */
    public GetSiteInfoVo getSiteInfo(String siteId){
        GetSiteInfoVo getSiteInfoVo = new GetSiteInfoVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/getSiteInfo";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            getSiteInfoVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), GetSiteInfoVo.class);
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return getSiteInfoVo;
    }

    /**
     * 添加快站域名站点
     * @author jitwxs
     * @param siteName-站点名称
     * @date 2022/1/16 17:16
     */
    public CreateSiteVo createSite(String siteName){
        CreateSiteVo createSiteVo = new CreateSiteVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/createSite";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteName", siteName);
        param.add("domain", siteName); //默认站点名称和域名一样
        param.add("siteType", "FAST"); //极速版
        param.add("httpsForward", String.valueOf(false)); //不开启域名https跳转
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();

        logger.info("----创建域名返回对象值----" + JSONObject.toJSONString(kuaiZhanResulit));

        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            createSiteVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), CreateSiteVo.class);
        }else{
            logger.error("创建域名失败,error={}", kuaiZhanResulit == null ? "返回对于为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return createSiteVo;
    }

    /**
     * 开通套餐授权
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public Boolean openBusinessPackage(String siteId){
        String url = "https://cloud.kuaizhan.com/api/v1/agent/openBusinessPackage";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        param.add("businessType", "SITE_EXCLUSIVE_YEAR"); //站点尊享包年套餐
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            return true;
        }else{
            logger.error("--开通套餐授权异常,error={}", kuaiZhanResulit == null?"开通套餐返回对象为空":kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
    }


    /**
     * 发布站点
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public PublishSiteVo publishSite(String siteId){
        PublishSiteVo publishSiteVo = new PublishSiteVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/publishSite";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            publishSiteVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), PublishSiteVo.class);
        }else{
            logger.error("--发布站点异常,error={}", kuaiZhanResulit == null? "发布站点返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return publishSiteVo;
    }

    /**
     * 发布页面
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public PublishPageVo publishPage(String siteId){
        PublishPageVo publishPageVo = new PublishPageVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/publishPage";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            publishPageVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), PublishPageVo.class);
        }else{
            logger.error("--发布页面异常,error={}", kuaiZhanResulit == null? "发布页面返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return publishPageVo;
    }

    /**
     * 更新页面js
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public Boolean modifyPageJs(String siteId, String content){
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/modifyPageJs";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        param.add("content", content);
        param.add("isEncryptContent", "false"); //不加密
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            return true;
        }else{
            logger.error("--更新页面js异常,error={}", kuaiZhanResulit == null? "更新页面js返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
    }

    /**
     * 批量更新页面js
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public Boolean batchModifyPageJs(List<Long> siteIds, String content){
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteIds", JSONObject.toJSONString(siteIds));
        param.add("content", content);
        param.add("isSecure", "false"); //不加密
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        //param.add("sign", sign);

        String url = "https://cloud.kuaizhan.com/api/v1/tbk/batchModifyPublishPageJs?appKey=" + appKey + "&sign=" + sign;
        //删除appKey作为body参数
        JSONObject bodyPara = new JSONObject();
        bodyPara.put("siteIds", siteIds);
        bodyPara.put("content", content);
        bodyPara.put("isSecure", "false"); //不加密
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> request = new HttpEntity<>(bodyPara, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            return true;
        }else{
            logger.error("--批量更新页面js异常,error={}", kuaiZhanResulit == null? "批量更新页面js返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
    }

    /**
     * 修改站点名称
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public Boolean updateSiteSetting(String siteId, String siteName){
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/updateSiteSetting";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        param.add("siteName", siteName);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            return true;
        }else{
            logger.error("--修改站点名称异常,error={}", kuaiZhanResulit == null? "修改站点名称返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
    }


    /**
     * 修改域名
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public ChangeDomainVo changeDomain(String siteId, String domain){
        ChangeDomainVo changeDomainVo = new ChangeDomainVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/changeDomain";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        param.add("domain", domain);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            changeDomainVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), ChangeDomainVo.class);
        }else{
            logger.error("--修改域名异常,error={}", kuaiZhanResulit == null? "修改域名返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return changeDomainVo;
    }

    /**
     * 检测域名是否封禁（false-未封禁）
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public CheckDomainBanVo checkDomainBan(String domain){
        CheckDomainBanVo checkDomainBanVo = new CheckDomainBanVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/checkDomainBan";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("domain", domain);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            checkDomainBanVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), CheckDomainBanVo.class);
        }else{
            logger.error("--检测域名是否封禁异常,error={}", kuaiZhanResulit == null? "检测域名是否封禁返回对象为空" : kuaiZhanResulit.getMsg());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
        return checkDomainBanVo;
    }

    /**
     * 获取站点当月被封禁的次数
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public GetSiteBanCountVo getSiteBanCount(String siteId){
        GetSiteBanCountVo getSiteBanCountVo = new GetSiteBanCountVo();
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/getSiteBanCount";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            getSiteBanCountVo = JSONObject.parseObject(JSONObject.toJSONString(kuaiZhanResulit.getData()), GetSiteBanCountVo.class);
        }

        return getSiteBanCountVo;
    }


    /**
     * 开启域名Https跳转
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    public Boolean changeDomainHttpsForward(String siteId, String domain, Boolean httpsForward){
        String url = "https://cloud.kuaizhan.com/api/v1/tbk/changeDomainHttpsForward";
        MultiValueMap<String,String> param = new LinkedMultiValueMap<>();
        String appKey = sysConfigMapper.selectByKey("kzappkey");
        String secret = sysConfigMapper.selectByKey("kzappsecret");
        param.add("appKey", appKey);
        param.add("siteId", siteId);
        param.add("domain", domain);
        param.add("httpsForward", String.valueOf(httpsForward));
        String sign = signTopRequest(param.toSingleValueMap(), secret);
        param.add("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<KuaiZhanResulit> response = restTemplate.postForEntity(url, request, KuaiZhanResulit.class);
        KuaiZhanResulit kuaiZhanResulit = response.getBody();
        if(kuaiZhanResulit != null && "200".equals(kuaiZhanResulit.getCode())){
            return true;
        }else{
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, kuaiZhanResulit.getMsg());
        }
    }

}
